<template>
  <div class="modern-app-card" :class="{ featured: featured }">
    <!-- 封面区域 -->
    <div class="card-cover">
      <div class="cover-image" :style="{ backgroundImage: getCoverImageStyle() }">
        <!-- 渐变遮罩 -->
        <div class="cover-overlay"></div>
        
        <!-- 悬浮操作按钮 -->
        <div class="hover-overlay">
          <div class="action-buttons">
            <button class="action-btn primary-btn" @click="handleViewClick">
              查看
            </button>
            <button v-if="isAdmin" class="action-btn secondary-btn" @click="$emit('edit', app)">
              编辑
            </button>
            <button v-if="showDeployButton" class="action-btn deploy-btn" @click="$emit('deploy', app)">
              部署
            </button>
          </div>
        </div>

        <!-- 应用类型标签 -->
        <div class="app-type-tag">
          {{ getTypeName(app.codeGenType) }}
        </div>

        <!-- 精选标识 -->
        <div v-if="featured || app.priority === 100" class="featured-badge">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor">
            <polygon
              points="12,2 15.09,8.26 22,9.27 17,14.14 18.18,21.02 12,17.77 5.82,21.02 7,14.14 2,9.27 8.91,8.26"
            />
          </svg>
          精选
        </div>

        <!-- 部署状态 -->
        <div v-if="app.deployKey" class="deploy-status">
          <div class="status-dot"></div>
          已部署
        </div>

        <!-- 公开状态 -->
        <div v-if="showPublicStatus" class="public-status" :class="{ private: !isPublic }">
          <EyeOutlined v-if="isPublic" />
          <EyeInvisibleOutlined v-else />
          {{ isPublic ? '公开' : '私有' }}
        </div>
      </div>
    </div>

    <!-- 内容区域 -->
    <div class="card-content">
      <!-- 应用信息 -->
      <div class="app-info">
        <h3 class="app-title" @click="handleNameClick">{{ app.appName }}</h3>
        <p class="app-description">{{ app.initPrompt || '暂无描述' }}</p>
      </div>

      <!-- 用户信息 -->
      <div v-if="showUser && app.user" class="user-info" @click="$emit('viewUser', app.user)">
        <div class="user-avatar">
          <a-avatar :src="app.user.userAvatar" :size="36">
            {{ app.user.userName?.charAt(0) }}
          </a-avatar>
          <div v-if="app.user.userRole === 'admin'" class="admin-crown">
            <CrownOutlined />
          </div>
        </div>
        <div class="user-details">
          <span class="user-name">{{ app.user.userName }}</span>
          <span class="publish-time">{{ formatDate(app.createTime) }}</span>
        </div>
      </div>

      <!-- 公开状态切换 -->
      <div v-if="showPublicToggle && canManageApp" class="public-toggle-section">
        <div class="toggle-item">
          <div class="toggle-label">
            <EyeOutlined v-if="isPublic" />
            <EyeInvisibleOutlined v-else />
            <span>{{ isPublic ? '公开显示' : '私有应用' }}</span>
          </div>
          <a-switch 
            :checked="isPublic" 
            @change="handlePublicToggle"
            :loading="publicToggleLoading"
          />
        </div>
        <p class="toggle-description">
          {{ isPublic ? '应用已在应用广场公开展示' : '应用仅自己可见，开启后将在应用广场展示' }}
        </p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'
import {
  CrownOutlined,
  GlobalOutlined,
  MobileOutlined,
  DesktopOutlined,
  CodeOutlined,
  EyeOutlined,
  EyeInvisibleOutlined
} from '@ant-design/icons-vue'
import defaultCoverImage from '@/assets/default.jpeg'
import { updateAppPublicStatus } from '@/api/yingyongjiekou'
import { message } from 'ant-design-vue'

interface Props {
  app: API.AppVO
  showUser?: boolean
  featured?: boolean
  isAdmin?: boolean
  currentUserId?: number | string // 新增：当前用户ID
  showPublicToggle?: boolean // 新增：是否显示公开状态切换
}

const props = withDefaults(defineProps<Props>(), {
  showUser: false,
  featured: false,
  isAdmin: false,
  showPublicToggle: false
})

const emit = defineEmits<{
  view: [app: API.AppVO]
  edit: [app: API.AppVO]
  delete: [app: API.AppVO]
  chat: [app: API.AppVO]
  deploy: [app: API.AppVO]
  toggleFeatured: [app: API.AppVO]
  togglePublic: [app: API.AppVO, isPublic: boolean] // 新增：切换公开状态事件
  viewUser: [user: API.UserBasicVO]
}>()

// 响应式状态
const publicToggleLoading = ref(false)

// 计算属性
// 判断是否显示部署按钮
const showDeployButton = computed(() => {
  // 如果应用已经部署，不显示部署按钮
  if (props.app.deployKey) return false
  
  // 如果是管理员，总是显示部署按钮
  if (props.isAdmin) return true
  
  // 如果是应用的创建者，显示部署按钮
  if (props.currentUserId && props.app.userId === props.currentUserId) return true
  
  return false
})

// 判断是否为公开应用
const isPublic = computed(() => {
  return props.app.isPublic === 1
})

// 判断是否显示公开状态
const showPublicStatus = computed(() => {
  // 在应用广场或者是自己的应用时显示公开状态
  return props.showUser || (props.currentUserId && props.app.userId === props.currentUserId)
})

// 判断是否可以管理该应用
const canManageApp = computed(() => {
  // 是管理员或者是应用的创建者
  return props.isAdmin || (props.currentUserId && props.app.userId === props.currentUserId)
})

// 处理公开状态切换
const handlePublicToggle = async (checked: boolean) => {
  if (!props.app.id) return
  
  publicToggleLoading.value = true
  try {
    const response = await updateAppPublicStatus({
      appId: props.app.id,
      isPublic: checked ? 1 : 0
    })
    
    if (response.data.code === 200) {
      message.success(checked ? '应用已公开' : '应用已设为私有')
      emit('togglePublic', props.app, checked)
    } else {
      message.error(response.data.message || '操作失败')
    }
  } catch (error) {
    console.error('切换公开状态失败:', error)
    message.error('操作失败，请重试')
  } finally {
    publicToggleLoading.value = false
  }
}

// 获取封面图片样式
const getCoverImageStyle = () => {
  // 如果应用有封面图片，使用应用的封面
  if (props.app.cover) {
    return `url("${props.app.cover}")`
  }
  
  // 否则使用默认图片
  return `url("${defaultCoverImage}")`
}

// 获取应用类型图标
const getTypeIcon = (type?: string) => {
  const iconMap = {
    web: GlobalOutlined,
    mobile: MobileOutlined,
    desktop: DesktopOutlined,
    api: CodeOutlined
  }
  return iconMap[type as keyof typeof iconMap] || CodeOutlined
}

// 获取应用类型名称
const getTypeName = (type?: string) => {
  const nameMap = {
    web: 'Web应用',
    mobile: '移动应用',
    desktop: '桌面应用',
    api: 'API服务'
  }
  return nameMap[type as keyof typeof nameMap] || '应用'
}

// 格式化日期
const formatDate = (dateStr?: string) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  const now = new Date()
  const diff = now.getTime() - date.getTime()

  const minute = 60 * 1000
  const hour = 60 * minute
  const day = 24 * hour
  const week = 7 * day
  const month = 30 * day

  if (diff < minute) return '刚刚'
  if (diff < hour) return `${Math.floor(diff / minute)}分钟前`
  if (diff < day) return `${Math.floor(diff / hour)}小时前`
  if (diff < week) return `${Math.floor(diff / day)}天前`
  if (diff < month) return `${Math.floor(diff / week)}周前`

  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'short',
    day: 'numeric'
  })
}

// 处理应用名称点击
const handleNameClick = () => {
  emit('view', props.app)
}

// 处理查看按钮点击
const handleViewClick = () => {
  emit('view', props.app)
}
</script>

<style scoped>
.modern-app-card {
  position: relative;
  background: white;
  border-radius: 16px;
  box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  overflow: hidden;
  cursor: pointer;
  border: 1px solid #f0f2f5;
  backdrop-filter: blur(10px);
}

.modern-app-card:hover {
  box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
  transform: translateY(-4px);
  border-color: rgba(24, 144, 255, 0.2);
}

.modern-app-card.featured {
  border: 2px solid #ffd700;
  box-shadow: 0 8px 32px rgba(255, 215, 0, 0.15);
}

/* 封面区域 */
.card-cover {
  position: relative;
  width: 100%;
  height: 192px;
  overflow: hidden;
  border-radius: 16px 16px 0 0;
}

.cover-image {
  width: 100%;
  height: 100%;
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  position: relative;
  transition: transform 0.5s ease;
}

.modern-app-card:hover .cover-image {
  transform: scale(1.05);
}

/* 渐变遮罩 */
.cover-overlay {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background: linear-gradient(to top, rgba(0, 0, 0, 0.3), transparent, transparent);
  opacity: 0;
  transition: opacity 0.3s ease;
}

.modern-app-card:hover .cover-overlay {
  opacity: 1;
}

/* 悬浮操作按钮 */
.hover-overlay {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: all 0.3s ease;
  background: rgba(0, 0, 0, 0.4);
  backdrop-filter: blur(4px);
}

.modern-app-card:hover .hover-overlay {
  opacity: 1;
}

.action-buttons {
  display: flex;
  align-items: center;
  gap: 12px;
  animation: slideUp 0.3s ease-out;
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 按钮样式 */
.action-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 12px 20px;
  border-radius: 12px;
  font-weight: 500;
  font-size: 14px;
  transition: all 0.2s ease;
  border: none;
  cursor: pointer;
  backdrop-filter: blur(10px);
  min-width: 80px;
}

.primary-btn {
  background: #3b82f6;
  color: white;
  box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
}

.primary-btn:hover {
  background: #2563eb;
  transform: scale(1.05);
  box-shadow: 0 8px 25px rgba(59, 130, 246, 0.4);
}

.secondary-btn {
  background: rgba(255, 255, 255, 0.9);
  color: #374151;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
}

.secondary-btn:hover {
  background: white;
  color: #111827;
  transform: scale(1.05);
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
}

.deploy-btn {
  background: linear-gradient(to right, #10b981, #059669);
  color: white;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
}

.deploy-btn:hover {
  background: linear-gradient(to right, #059669, #047857);
  transform: scale(1.05);
  box-shadow: 0 4px 15px rgba(34, 197, 94, 0.3);
}

/* 移除不需要的样式 */
.icon-btn {
  display: none;
}

/* 底部操作区 - 移除 */
.bottom-actions,
.action-group,
.star-btn,
.more-btn,
.modern-dropdown {
  display: none;
}

/* 应用类型标签 */
.app-type-tag {
  position: absolute;
  top: 12px;
  left: 12px;
  padding: 4px 12px;
  background: rgba(255, 255, 255, 0.9);
  color: #374151;
  font-size: 12px;
  font-weight: 500;
  border-radius: 9999px;
  backdrop-filter: blur(10px);
  transition: all 0.3s ease;
}

.modern-app-card:hover .app-type-tag {
  background: white;
  color: #111827;
  transform: scale(1.05);
}

/* 精选标识 */
.featured-badge {
  position: absolute;
  top: 12px;
  right: 12px;
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 4px 12px;
  background: linear-gradient(to right, #fbbf24, #eab308);
  color: white;
  font-size: 12px;
  font-weight: 500;
  border-radius: 9999px;
  box-shadow: 0 4px 15px rgba(251, 191, 36, 0.3);
  animation: glow 2s ease-in-out infinite alternate;
}

@keyframes glow {
  from {
    box-shadow: 0 4px 15px rgba(251, 191, 36, 0.3);
  }
  to {
    box-shadow: 0 4px 25px rgba(251, 191, 36, 0.5);
  }
}

/* 部署状态 */
.deploy-status {
  position: absolute;
  bottom: 12px;
  right: 12px;
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 4px 12px;
  background: rgba(34, 197, 94, 0.9);
  color: white;
  font-size: 12px;
  font-weight: 500;
  border-radius: 9999px;
  backdrop-filter: blur(10px);
}

.status-dot {
  width: 8px;
  height: 8px;
  background: #86efac;
  border-radius: 50%;
  animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
}

@keyframes pulse {
  0%, 100% {
    opacity: 1;
  }
  50% {
    opacity: .5;
  }
}

/* 公开状态 */
.public-status {
  position: absolute;
  top: 12px;
  left: 12px;
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 4px 12px;
  background: rgba(255, 255, 255, 0.9);
  color: #374151;
  font-size: 12px;
  font-weight: 500;
  border-radius: 9999px;
  backdrop-filter: blur(10px);
  border: 1px solid #e5e7eb;
  box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.05);
}

.public-status.private {
  color: #ef4444;
  border-color: #ef4444;
}

/* 内容区域 */
.card-content {
  padding: 20px;
}

.card-content > * + * {
  margin-top: 16px;
}

/* 应用信息 */
.app-info {
  margin-bottom: 8px;
}

.app-title {
  font-size: 18px;
  font-weight: 600;
  color: #111827;
  line-height: 1.25;
  transition: color 0.2s ease;
  cursor: pointer;
  margin: 0;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.app-title:hover {
  color: #2563eb;
}

.app-description {
  font-size: 14px;
  color: #6b7280;
  line-height: 1.5;
  margin: 8px 0 0 0;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

/* 用户信息 */
.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  background: #f9fafb;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.user-info:hover {
  background: #f3f4f6;
  transform: scale(1.02);
}

.user-avatar {
  position: relative;
}

.admin-crown {
  position: absolute;
  top: -4px;
  right: -4px;
  width: 20px;
  height: 20px;
  background: #fbbf24;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 12px;
}

.user-details {
  display: flex;
  flex-direction: column;
}

.user-name {
  font-size: 14px;
  font-weight: 500;
  color: #111827;
  margin: 0;
}

.publish-time {
  font-size: 12px;
  color: #6b7280;
  margin: 2px 0 0 0;
}

/* 公开状态切换 */
.public-toggle-section {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #e5e7eb;
  display: flex;
  align-items: center;
  gap: 12px;
}

.toggle-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.toggle-label {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 14px;
  color: #374151;
}

.toggle-description {
  font-size: 12px;
  color: #6b7280;
  margin-left: 24px;
}

/* 响应式设计 */
@media (max-width: 640px) {
  .modern-app-card {
    border-radius: 12px;
  }
  
  .card-cover {
    height: 160px;
  }
  
  .card-content {
    padding: 16px;
  }
  
  .action-buttons {
    flex-direction: column;
    gap: 8px;
  }
  
  .primary-btn,
  .secondary-btn {
    padding: 12px 24px;
    font-size: 16px;
  }
}

/* 深色模式支持 */
@media (prefers-color-scheme: dark) {
  .modern-app-card {
    background: #1f2937;
    border-color: #374151;
  }
  
  .app-title {
    color: #f3f4f6;
  }
  
  .app-description {
    color: #d1d5db;
  }
  
  .user-info {
    background: #374151;
  }
  
  .user-info:hover {
    background: #4b5563;
  }
}
</style>
